<template>
  <div class="auto-generate-paper">
    <el-button type="primary" @click="showDialog = true">自动组卷</el-button>

    <el-dialog
      title="自动组卷配置"
      :visible.sync="showDialog"
      width="900px"
      @close="resetForm"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="120px"
        label-position="right"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="试卷名称" prop="paperName">
              <el-input v-model="form.paperName" placeholder="请输入试卷名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类" prop="categoryId">
              <InputAndSearchWithTree
                v-model="form.categoryId"
                placeholder="请选择分类"
                @change="handleCategoryChange"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="试卷描述" prop="description">
          <el-input
            type="textarea"
            v-model="form.description"
            placeholder="请输入试卷描述"
          ></el-input>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="总分" prop="totalScore">
              <el-input-number
                v-model="form.totalScore"
                :min="60"
                :max="200"
                :step="10"
                @change="calculateTotalScore"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="及格分数" prop="passScore">
              <el-input-number
                v-model="form.passScore"
                :min="0"
                :max="form.totalScore"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span>题目数量与分数配置</span>
          </div>

          <el-row :gutter="20" v-for="(item, type) in questionTypes" :key="type">
            <el-col :span="12">
              <el-form-item :label="`${item.label}数量`" :prop="`questionCountConfig.${type}Count`">
                <el-input-number
                  v-model="form.questionCountConfig[`${type}Count`]"
                  :min="0"
                  :max="50"
                  @change="calculateTotalScore"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="`每题分数`" :prop="`questionScoreConfig.${type}Score`">
                <el-input-number
                  v-model="form.questionScoreConfig[`${type}Score`]"
                  :min="1"
                  :max="20"
                  @change="calculateTotalScore"
                ></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span>难度分布配置</span>
            <el-button
              style="float: right; padding: 3px 0"
              type="text"
              @click="useDefaultDifficulty"
            >使用默认配置</el-button>
          </div>
          <el-form-item label="容易题比例" prop="difficultyConfig.easyRatio">
            <el-slider
              v-model="form.difficultyConfig.easyRatio"
              :min="0"
              :max="1"
              :step="0.1"
              :format-tooltip="formatRatio"
            ></el-slider>
          </el-form-item>

          <el-form-item label="偏易题比例" prop="difficultyConfig.slightlyEasyRatio">
            <el-slider
              v-model="form.difficultyConfig.slightlyEasyRatio"
              :min="0"
              :max="1"
              :step="0.1"
              :format-tooltip="formatRatio"
            ></el-slider>
          </el-form-item>

          <el-form-item label="中等题比例" prop="difficultyConfig.mediumRatio">
            <el-slider
              v-model="form.difficultyConfig.mediumRatio"
              :min="0"
              :max="1"
              :step="0.1"
              :format-tooltip="formatRatio"
            ></el-slider>
          </el-form-item>

          <el-form-item label="较难题比例" prop="difficultyConfig.slightlyHardRatio">
            <el-slider
              v-model="form.difficultyConfig.slightlyHardRatio"
              :min="0"
              :max="1"
              :step="0.1"
              :format-tooltip="formatRatio"
            ></el-slider>
          </el-form-item>

          <el-form-item label="困难题比例" prop="difficultyConfig.hardRatio">
            <el-slider
              v-model="form.difficultyConfig.hardRatio"
              :min="0"
              :max="1"
              :step="0.1"
              :format-tooltip="formatRatio"
            ></el-slider>
          </el-form-item>
        </el-card>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="showDialog = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 试卷预览弹窗 -->
    <paper-preview
      :visible.sync="previewVisible"
      :paper-data="paperData"
      @export="handleExport"
    />
  </div>
</template>

<script>
import InputAndSearchWithTree from '@/components/InputAndSearchWithTree'
import PaperPreview from './PaperPreview'
import { autoGeneratePaper } from '@/api/paper/paper'

export default {
  name: 'AutoGeneratePaper',
  components: {
    InputAndSearchWithTree,
    PaperPreview
  },
  data() {
    const validateRatioSum = (rule, value, callback) => {
      const total = this.form.difficultyConfig.easyRatio +
        this.form.difficultyConfig.slightlyEasyRatio +
        this.form.difficultyConfig.mediumRatio +
        this.form.difficultyConfig.slightlyHardRatio +
        this.form.difficultyConfig.hardRatio

      if (Math.abs(total - 1) > 0.0001) {
        callback(new Error('难度比例总和必须等于1'))
      } else {
        callback()
      }
    }

    return {
      showDialog: false,
      previewVisible: false,
      loading: false,
      paperData: null,
      questionTypes: {
        singleChoice: { label: '单选题' },
        multipleChoice: { label: '多选题' },
        fillBlank: { label: '填空题' },
        trueFalse: { label: '判断题' },
        essay: { label: '问答题' }
      },
      form: {
        paperName: '',
        description: '',
        categoryId: null,
        totalScore: 100,
        passScore: 60,
        questionCountConfig: {
          singleChoiceCount: 20,
          multipleChoiceCount: 10,
          fillBlankCount: 5,
          trueFalseCount: 5,
          essayCount: 2
        },
        questionScoreConfig: {
          singleChoiceScore: 2,
          multipleChoiceScore: 4,
          fillBlankScore: 2,
          trueFalseScore: 1,
          essayScore: 10
        },
        difficultyConfig: {
          easyRatio: 0.2,
          slightlyEasyRatio: 0.2,
          mediumRatio: 0.2,
          slightlyHardRatio: 0.2,
          hardRatio: 0.2
        }
      },
      rules: {
        paperName: [
          { required: true, message: '请输入试卷名称', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择分类', trigger: 'change' }
        ],
        'difficultyConfig.easyRatio': [
          { validator: validateRatioSum, trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    formatRatio(val) {
      return `${val * 100}%`
    },

    useDefaultDifficulty() {
      this.form.difficultyConfig = {
        easyRatio: 0.2,
        slightlyEasyRatio: 0.2,
        mediumRatio: 0.2,
        slightlyHardRatio: 0.2,
        hardRatio: 0.2
      }
    },

    calculateTotalScore() {
      // 自动计算总分
      const { questionCountConfig, questionScoreConfig } = this.form
      this.form.totalScore =
        (questionCountConfig.singleChoiceCount || 0) * (questionScoreConfig.singleChoiceScore || 0) +
        (questionCountConfig.multipleChoiceCount || 0) * (questionScoreConfig.multipleChoiceScore || 0) +
        (questionCountConfig.fillBlankCount || 0) * (questionScoreConfig.fillBlankScore || 0) +
        (questionCountConfig.trueFalseCount || 0) * (questionScoreConfig.trueFalseScore || 0) +
        (questionCountConfig.essayCount || 0) * (questionScoreConfig.essayScore || 0)
    },

    handleCategoryChange(node) {
      console.log('Selected category:', node)
    },

    resetForm() {
      this.$refs.form.resetFields()
    },

    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          autoGeneratePaper(this.form)
            .then(response => {
              this.paperData = response.data
              this.previewVisible = true
              this.showDialog = false
              this.$message.success('组卷成功')
            })
            .catch(() => {
              this.$message.error('组卷失败')
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },

    handleExport(type) {
      // 这里实现导出逻辑
      console.log('Export paper as:', type)
      this.$message.success(`试卷已导出为${type}格式`)
    }
  }
}
</script>

<style lang="scss" scoped>
.auto-generate-paper {
  display: inline-block;
}

.box-card {
  margin-bottom: 20px;

  ::v-deep .el-card__header {
    padding: 10px 20px;
    font-weight: bold;
    background-color: #f5f7fa;
  }
}

.el-slider {
  margin-top: 10px;
  margin-bottom: 10px;
}

.el-row {
  margin-bottom: 10px;

  &:last-child {
    margin-bottom: 0;
  }
}
</style>
